package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumer
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/6/29 14:07
 * @Version V1.0
 **/
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        //2,创建随机队列 创建交换机
        String queue = UUID.randomUUID().toString();//随机32位16进制字符串
        c.queueDeclare(queue, false,true,true,null);
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);

        System.out.println("输入绑定键,用空格隔开: ");
        String s = new Scanner(System.in).nextLine();
        String[] a
                = s.split("\\s+");//  \s+正则表达式,表示一到多个空白字符
        for (String k : a) {
            c.queueBind(queue, "topic_logs", k);

        }

        //3,正常懂队列接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {

            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new  String(message.getBody());
                //取出消息上携带的路由键
                String k = message.getEnvelope().getRoutingKey();
                System.out.println(k+"-收到: "+s);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {

            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        c.basicConsume(queue, true, deliverCallback,cancelCallback);


    }
}
